<?php
namespace app\admin\controller;
use cmf\controller\AdminBaseController;
use think\Db;
use think\paginator\driver\Bootstrap;

class ListenController extends AdminBaseController
{
	public function index()
	{
		$content = hook_one('admin_adaccount_index_view');
		if (!empty($content)) {
			return $content;
		}

		$where = ['admin_id' => cmf_get_current_admin_id(),'parent_id' => 0];

		$parent = Db::name('listen')->where($where)->select()->toArray();

		foreach ($parent as $key => $value) {
			$parent[$key]['fanpages'] = Db::name('listen')->where('parent_id',$value['id'])->select()->toArray();
			$parent[$key]['username'] = Db::name('user')->field('user_login')->where('id',$value['admin_id'])->find();
		}

		//分页
        $curpage = input('page') ? input('page') : 1;//当前第x页，有效值为：1,2,3,4,5...
        $listRow = 20;//每页行记录
        $showdata = array_slice($parent, ($curpage - 1)*$listRow, $listRow,true);
        
        $p = Bootstrap::make($showdata, $listRow, $curpage, count($parent), false, [
            'var_page' => 'page',
            'path'     => url('/admin/listen/index'),//这里根据需要修改url
            'query'    => request()->param(),
            'fragment' => '',
        ]);
        
        $p->appends($_GET);

        $this->assign('alllist',$p);
        $this->assign('plistpage', $p->render());
		return $this->fetch();
	}

	public function add()
	{
		return $this->fetch();
	}

	public function addPost()
	{

		if ($this->request->isPost()) {
			$data = TrimArray(input('post.'));

			//验证信息
			$result = $this->validate(
			    [
			        'domain'  		=> $data['domain'],
			        'phone' 		=> $data['phone'],
			    ],
			    [
			        'domain'  		=> 'require',
			        'phone' 		=> 'require|length:11',
			    ]);
			if(true !== $result){
			    // 验证失败 输出错误信息
			    $this->error($result);
			}

			$allText = Db::name('listen')->field('text')->select()->toArray();

			if ($allText) {
				foreach ($allText as $key => $value) {
					$allTexts[] = $value['text'];
				}
			}

			if (!isset($data['fanpages'])) {
				if (isset($allTexts)) {
					if (in_array($data['domain'], $allTexts)) {
						$this->error($data['domain'].'   已存在');
					}
				}

				//添加域名
				$parentData = [
					'text'		=> $data['domain'],
					'phone'		=> $data['phone'],
					'is_listen'	=> $data['is_listen'],
					'admin_id'	=> cmf_get_current_admin_id(),
					'status'	=> 1,
					'parent_id'	=> 0,
				];

				$re = Db::name('listen')->insert($parentData);
				if ($re) {
					$this->success('添加成功');
				}else{
					$this->error('添加失败');
				}

			}else{
				foreach ($data['fanpages'] as $fk => $fv) {
					if (isset($allTexts)) {
						if (in_array($data['domain'], $allTexts) || in_array($fv, $allTexts)) {
							$this->error($data['domain'].'   已存在');
						}
					}
				}

				//开启事务处理
				Db::startTrans();
				try {
					//添加域名
					$parentData = [
						'text'		=> $data['domain'],
						'phone'		=> $data['phone'],
						'is_listen'	=> $data['is_listen'],
						'admin_id'	=> cmf_get_current_admin_id(),
						'status'	=> 1,
						'parent_id'	=> 0,
					];

					Db::name('listen')->insert($parentData);
					$id = Db::name('listen')->getLastInsID();

					foreach (array_unique($data['fanpages']) as $k => $v) {
						$sonData[$k]['text'] 		= $v;
						$sonData[$k]['phone'] 		= $data['phone'];
						$sonData[$k]['is_listen'] 	= $data['is_listen'];
						$sonData[$k]['status'] 		= 1;
						$sonData[$k]['parent_id'] 	= $id;
						$sonData[$k]['admin_id']	= cmf_get_current_admin_id();
					}

					Db::name('listen')->insertAll($sonData);

					Db::commit();
					

				} catch (Exception $e) {
					// 回滚事务
			    	Db::rollback();
			    	$this->error('添加失败');
				}

				$this->success('添加成功' , url("Listen/index"));
			}
		}
	}

	public function edit()
	{
		$content = hook_one('admin_domainname_edit_view');

		if (!empty($content)) {
			return $content;
		}

		$id = (int)input('param.id');

		$data = Db::name('listen')->where('id',$id)->find();

		$data['fanpages'] = Db::name('listen')->where('parent_id',$id)->select()->toArray();

		$this->assign('dolist',$data);
		return $this->fetch();
	}

	public function editPost()
	{
		if ($this->request->isPost()) {
			$data = input('post.');

			$parentData = [
				'id'		=> $data['id'],
				'text'		=> $data['domain'],
				'phone'		=> $data['phone'],
				'is_listen'	=> $data['is_listen'],
			];

			if (isset($data['fanpages'])) {
				//x先删除原有粉丝页信息,再添加进来
				//开启事务处理
				Db::startTrans();
				try {
					$res = Db::name('listen')->field('id')->where('parent_id',$data['id'])->select();

					foreach ($res as $rk => $rv) {
						$idArr[] = $rv['id'];
					}

					$re = Db::name('listen')->delete($idArr);
					
					foreach (array_unique($data['fanpages']) as $k => $v) {
							$sonData[$k]['text'] 		= $v;
							$sonData[$k]['phone'] 		= $data['phone'];
							$sonData[$k]['is_listen'] 	= $data['is_listen'];
							$sonData[$k]['status'] 		= 1;
							$sonData[$k]['parent_id'] 	= $data['id'];
							$sonData[$k]['admin_id']	= cmf_get_current_admin_id();
					}

					Db::name('listen')->insertAll($sonData);
					Db::name('listen')->update($parentData);

					Db::commit();
					
				} catch (Exception $e) {
					// 回滚事务
			    	Db::rollback();
			    	$this->error('修改失败');
				}
				$this->success('修改成功');
			}else{
				Db::name('listen')->update($parentData);
				$this->success('修改成功');
			}	

		}else{
			$this->error('未知错误');
		}
	}

	//假删除.隐藏显示
	public function delete()
	{
		$id = (int)input('param.id');
		//开启事务处理
		Db::startTrans();
		try{
			$res = Db::name('listen')->field('id')->where('parent_id',$id)->select();

			foreach ($res as $rk => $rv) {
				$idArr[] = $rv['id'];
			}

			Db::name('listen')->delete($id);
			Db::name('listen')->delete($idArr);

			Db::commit();
		} catch (\Exception $e) {
		    // 回滚事务
		    Db::rollback();
		    $this->error('删除失败');
		}
		$this->success('删除成功');
	}

}
